//
//  TDLoginViewController.m
//  TFB
//
//  Created by Nothing on 15/3/16.
//  Copyright (c) 2015年 TD. All rights reserved.
//

#import "TDLoginViewController.h"
#import "TDRegistViewController.h"
#import "TDForgetPwdViewController.h"
#import "TDCollectMoneyViewController.h"
#import "TDConvenientViewController.h"
#import "TDMoreViewController.h"
#import "TDUserCenterViewController.h"
#import "TDVerificationCodeViewController.h"
#import "TDWeiZhuanViewController.h"
#import "TDAppCenterViewController.h"
#import "TDHttpEngine.h"
#import "GTMBase64.h"
#include <CommonCrypto/CommonCryptor.h>
#import "CommonCrypto/CommonDigest.h"
#import <BlocksKit/UIAlertView+BlocksKit.h>

#define LOGIN_BTN_TAG 100
#define REGIET_BTN_TAG 101
#define FORGETPWD_BTN_TAG 102

#define USERNAMETF_TAG 200
#define USERPWD_TAG 201

@interface TDLoginViewController ()
{
    UITextField *_userNameTF;
    UITextField *_userPwdTF;
    UIView *_backgroundView;
    
    MKNetworkEngine *_mkNetworkEngine;
}
@end

@implementation TDLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationController.navigationBar.backgroundColor = [UIColor colorWithRed:31/255.0f green:121/255.0f blue:132/255.0f alpha:1.0f];
    
    self.title = @"登录";
    [self creatUI];
    
    NSString * strModel  = [UIDevice currentDevice].model;
    NSLog(@"xinghao    %@", strModel);
    
    [self remenberCustLogin];
    
    _mkNetworkEngine = [[MKNetworkEngine alloc] init];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated{
    
    
}

- (void)remenberCustLogin
{
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE]) {
        NSString *custMobile = [[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE];
        _userNameTF.text = custMobile;
    }
}

//#pragma mark - UITextFieldDelegate
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    if (textField == _userNameTF) {
//        // 四位加一个空格
//        if ([string isEqualToString:@""]) { // 删除字符
//            if ((textField.text.length - 2) % 5 == 0) {
//                textField.text = [textField.text substringToIndex:textField.text.length - 1];
//            }
//            return YES;
//        } else {
//            if (textField.text.length % 5 == 0) {
//                textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
//            }
//        }
//        return YES;
//    }
//    return YES;
//}

- (void)creatUI
{
    _backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SVFS.width, SVFS.height)];
    [self.view addSubview:_backgroundView];
    
    
    UIImageView *userNameBg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_input.png"]];
    userNameBg.frame = CGRectMake(8, 100, SVFS.width - 16, 44);
    userNameBg.userInteractionEnabled = YES;
    [_backgroundView addSubview:userNameBg];
    
    UIImageView *phoneImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_mobile"]];
    phoneImage.frame = CGRectMake(8, 7, 26, 30);
    [userNameBg addSubview:phoneImage];
    
    UIView *carveUpLine = [[UIView alloc] init];
    carveUpLine.backgroundColor = [UIColor colorWithRed:28/255.0f green:130/255.0f blue:168/255.0f alpha:1.0f];
    carveUpLine.frame = CGRectMake(phoneImage.frame.origin.x + phoneImage.frame.size.width + 8, 5, 1, 34);
    [userNameBg addSubview:carveUpLine];
    
    _userNameTF = [[UITextField alloc] init];
    _userNameTF.frame = CGRectMake(carveUpLine.frame.origin.x + carveUpLine.frame.size.width + 8, 0, userNameBg.bounds.size.width - (carveUpLine.frame.origin.x + carveUpLine.frame.size.width + 8), userNameBg.bounds.size.height);
    [_userNameTF addTarget:self action:@selector(tfEndEditWithTextField:) forControlEvents:UIControlEventEditingDidEndOnExit];
    _userNameTF.delegate = self;
    _userNameTF.tag = USERNAMETF_TAG;
    _userNameTF.placeholder = @"请输入用户名";
    [userNameBg addSubview:_userNameTF];
    
    
    
    UIImageView *userPwdBg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_input.png"]];
    userPwdBg.frame = CGRectMake(8, 10 + userNameBg.frame.size.height + userNameBg.frame.origin.y, SVFS.width - 16, 44);
    userPwdBg.userInteractionEnabled = YES;
    [_backgroundView addSubview:userPwdBg];
    
    UIImageView *pwdImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_pwd"]];
    pwdImage.frame = CGRectMake(8, 7, 26, 30);
    [userPwdBg addSubview:pwdImage];
    
    UIView *carveUpLinePwd = [[UIView alloc] init];
    carveUpLinePwd.backgroundColor = [UIColor colorWithRed:28/255.0f green:130/255.0f blue:168/255.0f alpha:1.0f];
    carveUpLinePwd.frame = CGRectMake(pwdImage.frame.origin.x + pwdImage.frame.size.width + 8, 5, 1, 34);
    [userPwdBg addSubview:carveUpLinePwd];
    
    _userPwdTF = [[UITextField alloc] init];
    _userPwdTF.frame = CGRectMake(carveUpLinePwd.frame.origin.x + carveUpLinePwd.frame.size.width + 8, 0, userPwdBg.bounds.size.width - (carveUpLinePwd.frame.origin.x + carveUpLinePwd.frame.size.width + 8), userPwdBg.bounds.size.height);
    [_userPwdTF addTarget:self action:@selector(tfClickWithTextField:) forControlEvents:UIControlEventEditingDidEndOnExit];
    _userPwdTF.tag = USERPWD_TAG;
    _userPwdTF.placeholder = @"请输入密码";
    _userPwdTF.secureTextEntry = YES;
    [userPwdBg addSubview:_userPwdTF];
    
    
    UIButton *registBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    registBtn.frame = CGRectMake(10, userPwdBg.frame.origin.y + userPwdBg.frame.size.height + 10, 50, 30);
    registBtn.tag = REGIET_BTN_TAG;
    registBtn.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [registBtn setTitle:@"注册" forState:0];
    [registBtn addTarget:self action:@selector(btnClickWithButton:) forControlEvents:UIControlEventTouchUpInside];
    [_backgroundView addSubview:registBtn];
    
    
    UIButton *forgetPwdBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    forgetPwdBtn.frame = CGRectMake(SVFS.width - 100, userPwdBg.frame.origin.y + userPwdBg.frame.size.height + 10, 90, 30);
    forgetPwdBtn.tag = FORGETPWD_BTN_TAG;
    forgetPwdBtn.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [forgetPwdBtn setTitle:@"忘记密码？" forState:0];
    [forgetPwdBtn addTarget:self action:@selector(btnClickWithButton:) forControlEvents:UIControlEventTouchUpInside];
    [_backgroundView addSubview:forgetPwdBtn];
    
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    loginBtn.frame = CGRectMake(10, userPwdBg.frame.origin.y + userPwdBg.frame.size.height + 50, SVFS.width - 20, 44);
    loginBtn.tag = LOGIN_BTN_TAG;
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"bg_btn"] forState:0];
    [loginBtn setTitle:@"登录" forState:0];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:0];
    [loginBtn addTarget:self action:@selector(btnClickWithButton:) forControlEvents:UIControlEventTouchUpInside];
    [_backgroundView addSubview:loginBtn];
    
}

#pragma mark MD5加密
-(NSString *)stringToMD5String:(NSString *)string;
{
    const char *cStr = [string UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}

- (void)btnClickWithButton:(UIButton *)sender
{
    
    switch (sender.tag) {
        case LOGIN_BTN_TAG:
        {
            [self.view endEditing:YES];
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            NSLog(@"login");
            
            /*
            [self creatMian];
            
            NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
            [dic setValue:@"13273901442" forKey:@"custMobile"];
            [dic setValue:@"01" forKey:@"codeType"];
            
            NSDictionary *diction = [self jsonWithDic:dic];
            MKNetworkOperation *operation = [_mkNetworkEngine operationWithURLString:@"http://192.168.0.59:8080/mpcctp/SY0001.json" params:diction httpMethod:@"POST"];
            __weak MKNetworkOperation *weakOperation = operation;
            [weakOperation addCompletionHandler:^(MKNetworkOperation *completedOperation) {
                NSLog(@"%@", weakOperation.responseString);
            } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
                NSLog(@"error---> %@\r errmasage--->%@", error, [error localizedDescription]);
            }];
            [_mkNetworkEngine enqueueOperation:operation];
             */
            
            //[self creatMian];
            
            
            [TDHttpEngine requestForLoginWithCustMobile:_userNameTF.text custPwd:[self stringToMD5String:_userPwdTF.text] complete:^(BOOL succeed, NSString *msg, NSString *cod) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if (succeed) {
                    [self creatMian];
                    [self checkVersion];
                }
                else{
                    [self.view makeToast:msg duration:2.0f position:@"center"];
                }
            }];
        }
            break;
            
        case REGIET_BTN_TAG:
        {
            NSLog(@"regist");
//            TDRegistViewController *registVC = [[TDRegistViewController alloc] init];
//            UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] init];
//            backBtn.title = @"返回";
//            self.navigationItem.backBarButtonItem = backBtn;
//            [self.navigationController pushViewController:registVC animated:YES];
            
            TDVerificationCodeViewController *verVC = [[TDVerificationCodeViewController alloc] init];
            verVC.verCodeType = VerRegist;
            verVC.isNeedMobileNum = YES;
            verVC.title = @"注册";
            [self.navigationController pushViewController:verVC animated:YES];
            
        }
            break;
            
        case FORGETPWD_BTN_TAG:
        {
            NSLog(@"forget");
//            TDForgetPwdViewController *forgetPwdVC = [[TDForgetPwdViewController alloc] init];
//            UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] init];
//            backBtn.title = @"返回";
//            self.navigationItem.backBarButtonItem = backBtn;
//            [self.navigationController pushViewController:forgetPwdVC animated:YES];
            TDVerificationCodeViewController *verVC = [[TDVerificationCodeViewController alloc] init];
            verVC.verCodeType = VerEditLoginPwd;
            verVC.isNeedMobileNum = YES;
            verVC.isForgetPwd = YES;
            verVC.title = @"找回登录密码";
            [self.navigationController pushViewController:verVC animated:YES];
        }
            break;
            
        default:
            break;
    }
    
}

- (void)tfClickWithTextField:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    
//    switch (textField.tag) {
//        case USERNAMETF_TAG:
//        {
//            NSLog(@"账号输入框");
//            
//            
//        }
//            break;
//            
//        case USERPWD_TAG:
//        {
//            NSLog(@"密码输入框");
//            if ([[UIDevice currentDevice].model isEqualToString:@"iPhone 4S"]) {
//                [UIView beginAnimations:nil context:nil];
//                [UIView animateWithDuration:1.0f animations:^{
//                    _backgroundView.frame = CGRectMake(_backgroundView.frame.origin.x, _backgroundView.frame.origin.y - 60, SVFS.width, SVFS.height);
//                }];
//                [UIView commitAnimations];
//            }
//        }
//            break;
//            
//        default:
//            break;
//    }
}

- (void)tfEndEditWithTextField:(UITextField *)textField
{
//    [UIView beginAnimations:nil context:nil];
//    [UIView animateWithDuration:1.0f animations:^{
//        _backgroundView.frame = CGRectMake(_backgroundView.frame.origin.x, _backgroundView.frame.origin.y + 20, SVFS.width, SVFS.height);
//    }];
//    [UIView commitAnimations];
}

- (void)checkVersion
{
    [TDHttpEngine requestFor_CHECKVERSION_WithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID] custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE] appVersion:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] appPlatform:@"1" complete:^(BOOL succeed, NSString *msg, id reqBody) {
        if (succeed) {
            NSInteger checkState = [reqBody[@"checkState"] integerValue];
            NSString *fileDesc = reqBody[@"fileDesc"];
            NSString *fileUrl = reqBody[@"fileUrl"];
            UIAlertView *alertView = [UIAlertView bk_alertViewWithTitle:@"有新版本更新" message:fileDesc];
            if (checkState == 1 || checkState == 2) {
                [alertView bk_addButtonWithTitle:@"更新" handler:^{
                    [[UIApplication  sharedApplication] openURL:[NSURL URLWithString:fileUrl]];
                    if (checkState == 2) {
                        exit(0);
                    }
                }];
                
                if (checkState == 1) {
                    [alertView bk_setCancelButtonWithTitle:@"取消" handler:^{
                        
                    }];
                }
                
                [alertView show];
            }
        }
    }];
}

- (void)creatMian
{
    TDAppCenterViewController * appcenterVC = [[TDAppCenterViewController alloc] init];
    appcenterVC.tabBarItem.title = @"应用中心";
    appcenterVC.tabBarItem.image = [[UIImage imageNamed:@"tab_appcenter"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    appcenterVC.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_appcenter_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UINavigationController *collectMoneyNav = [[UINavigationController alloc] initWithRootViewController:appcenterVC];
    collectMoneyNav.navigationBar.tintColor = [UIColor whiteColor];
    [collectMoneyNav.navigationBar setBarStyle:UIBarStyleBlack];
    

    
    TDConvenientViewController *convenientVC = [[TDConvenientViewController alloc] init];
    convenientVC.tabBarItem.image = [UIImage imageNamed:@"tab_bianmin"];
    convenientVC.tabBarItem.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0);
    UINavigationController *convenientNav = [[UINavigationController alloc] initWithRootViewController:convenientVC];
    [convenientNav.navigationBar setBarStyle:UIBarStyleBlackTranslucent];

    TDWeiZhuanViewController *weizhuanVC = [[TDWeiZhuanViewController alloc] init];
    weizhuanVC.tabBarItem.title = @"微赚";
    weizhuanVC.tabBarItem.image = [[UIImage imageNamed:@"main_vz"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    weizhuanVC.tabBarItem.selectedImage = [[UIImage imageNamed:@"on_main_vz"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UINavigationController *weizhuanNav = [[UINavigationController alloc] initWithRootViewController:weizhuanVC];
    weizhuanNav.navigationBar.tintColor = [UIColor whiteColor];
    [weizhuanNav.navigationBar setBarStyle:UIBarStyleBlackTranslucent];
    
    
    TDUserCenterViewController *usercenterVC = [[TDUserCenterViewController alloc] init];
    usercenterVC.tabBarItem.title = @"用户中心";
    usercenterVC.tabBarItem.image = [[UIImage imageNamed:@"tab_usercenter"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    usercenterVC.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_usercenter_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UINavigationController *businessNav = [[UINavigationController alloc] initWithRootViewController:usercenterVC];
    businessNav.navigationBar.tintColor = [UIColor whiteColor];
    [businessNav.navigationBar setBarStyle:UIBarStyleBlackTranslucent];
    
    
    
    TDMoreViewController *moreVC = [[TDMoreViewController alloc] init];
    moreVC.tabBarItem.title = @"更多";
    moreVC.tabBarItem.image = [[UIImage imageNamed:@"tab_more"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    moreVC.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_more_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UINavigationController *finaceNav = [[UINavigationController alloc] initWithRootViewController:moreVC];
    finaceNav.navigationBar.tintColor = [UIColor whiteColor];
    [finaceNav.navigationBar setBarStyle:UIBarStyleBlackTranslucent];

    
    
    
    UITabBarController *mainTBC = [[UITabBarController alloc] init];
    mainTBC.viewControllers = @[collectMoneyNav, businessNav, finaceNav];
#ifdef SHOW_WEIZHUAN
    mainTBC.viewControllers = @[collectMoneyNav, businessNav, weizhuanNav, finaceNav];
#endif
    mainTBC.navigationController.navigationBar.backgroundColor = [UIColor colorWithRed:31/255.0f green:121/255.0f blue:132/255.0f alpha:1.0f];
    [mainTBC.navigationItem setHidesBackButton:YES];
    //[self.navigationController pushViewController:mainTBC animated:YES];
    
    [mainTBC.viewControllers enumerateObjectsUsingBlock:^(UIViewController *obj, NSUInteger idx, BOOL *stop) {
        [obj.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} forState:UIControlStateSelected];
        obj.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -2);
    }];
    
    [UIView animateWithDuration:0.32f delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.view.frame = CGRectMake(-SVFS.width, SVFO.y, SVFS.width, SVFS.height);
    } completion:^(BOOL finished) {
        self.view.window.rootViewController = mainTBC;
        [self.view removeFromSuperview];
    }];
    

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (NSDictionary *)jsonWithDic:(id)sender
{
    NSMutableDictionary *jsonDic = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *smallDic = [NSMutableDictionary dictionaryWithObject:sender forKey:@"REQ_BODY"];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:smallDic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    [jsonDic setObject:jsonStr forKey:@"REQ_MESSAGE"];
    return jsonDic;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
